const merge = require("webpack-merge");
const path = require("path");
const fs = require('fs');
const random = require('string-random');
const dir = require("./dir");

const pathToName = require(path.join(dir.frameworkCommonDir, 'driver')).pathToName;
const resolve = require("./driver").resolve;
const webpackPromise = require("./driver").webpackPromise;


const common = require("./webpack.common.js");


// 构建前清理
const CleanWebpackPlugin = require("clean-webpack-plugin");
// HTML 模板
const HtmlWebpackPlugin = require("html-webpack-plugin");
// 纯静态资源复制
const CopyWebpackPlugin = require("copy-webpack-plugin");

module.exports = async (source_path) => {
    let source_name = pathToName(source_path);

    let app_file = path.join(resolve(source_path), 'app.js');

    if (!fs.existsSync(app_file)) {
        console.log(`未找到文件：${app_file}`);
        return;
    }

    let dll_js = [];
    let dll_css = [];
    let copy_configs = [
        {
            from: path.join(resolve(source_path), 'app.js'),
            to: path.join(dir.binDir, source_name, "framework/app.js"),
        },
        {
            from: path.join(resolve(source_path), 'public/favicon.ico'),
            to: path.join(dir.binDir, source_name, "favicon.ico"),
        }
    ];

    let app = require(app_file);

    for (let id in app.plugs) {
        let plug = app.plugs[id];
        let plug_path = plug.url;
        let plug_name = pathToName(plug_path);
        let file = path.join(dir.binDir, plug_name);
        if (fs.existsSync(file)) {
            copy_configs.push({
                from: path.join(dir.binDir, plug_name),
                to: path.join(dir.binDir, source_name, plug_name),
                ignore: [".*"]
            });
            file = path.join(dir.binDir, plug_name, 'dll/index.js');
            if (fs.existsSync(file)) {
                dll_js.push(path.join("./", plug_name, 'dll/index.js'));
            }
        }
    }

    let config = merge(common, {
        mode: "development",
        entry: {
            framework: path.join(dir.frameworkDir, 'main'),
        },
        output: {
            path: path.join(dir.binDir, source_name, 'framework'),
            publicPath: "./framework/",
            filename: "index.js",
            libraryTarget: "var"
        },
        // devtool: "source-map",
        plugins: [
            new CleanWebpackPlugin(),
            // HTML 模板
            new HtmlWebpackPlugin({
                template: path.join(resolve(source_path), 'public/index.html'),
                filename: path.join(dir.binDir, source_name, "index.html"),
                hash: true, // 为静态资源生成hash值
                title: app.title,
                dll_js: dll_js,
                dll_css: dll_css,
                rand_code: random(16),
            }),
            // 纯静态资源复制
            new CopyWebpackPlugin(copy_configs)
        ]
    });

    // console.log(config);

    await webpackPromise(config);


};
